/* eslint-disable react-hooks/exhaustive-deps */
"use client";

import { AssessType, ImproveDataLines } from "../../utils/publictype";
import {
  Button,
  Col,
  DatePicker,
  Form,
  Input,
  message,
  Row,
  Select,
} from "antd";
import { TableSetting } from "../../utils/publictype";
import { useEffect, useState } from "react";
import TextArea from "antd/es/input/TextArea";
import dayjs from "dayjs";

/**
 * @description Form封裝
 * @param {formProps} props
 * @param {singleRow} props.singleRow : 傳入表單的初始數據，必須是鍵值對對象，值可以為空代表新增；不為空代表修改
 * @param {formsettiing} props.formsettiing : 表單欄位設定，配置表單的欄位名稱、顯示名稱、欄位類型等等
 * @param {operation} props.operation : 表單操作方式，add或modify
 * @param {Submit} props.Submit : 表單提交事件
 * @param {Cancle} props.Cancle : 表單取消事件
 * @param {selectOptions} props.selectOptions : 表單中為select的數據。未完善點：當select出現聯動時，可以給出聯動的欄位名和函數，在父組件中修改state。再傳入props
 */
interface formProps {
  singleRow: AssessType | ImproveDataLines | any;
  formsettiing: TableSetting[];
  operation: string;
  Submit: (param: AssessType | ImproveDataLines | any, operation: string) => void;
  Cancle: () => void;
  selectOptions?: selectOption[];
  updateFlag: number
  check_flag?: boolean
}

export interface selectOption {
  key: string;
  value: any;
}

//select禁用
const disabledSet = ["project","purpose","limit_start","limit_end"];

export default function DetailForm(props: formProps) {
  const [form] = Form.useForm();
  const [operationRow, setOperationRow] = useState<AssessType |ImproveDataLines | any>();

  useEffect(() => {
    setOperationRow({ ...props.singleRow });
    if (props.operation === "modify") {
      Object.entries(props.singleRow).map(([key, value]) => {
        if (FormItemSet(key) === "datepicker") {
          form.setFieldValue(key,dayjs(value as string, "YYYY-MM-DD"))
        } else {
          form.setFieldValue(key, value);
        }
      });
    }
  }, [props.updateFlag]);

  const FormItemSet = (key: string): string => {
    let result = "";
    result = props.formsettiing.filter((item) => item.key === key)[0].formtypes;
    return result;
  };

  const FormItemLabel = (key: string): string => {
    let result = "";
    result = props.formsettiing.filter((item) => item.key === key)[0].title;
    return result;
  };

  const FormItemSelectOps = (key: string): [] => {
    let result = [];
    result =
      props.selectOptions?.filter((item) => item.key === key)[0] === undefined
        ? []
        : props.selectOptions?.filter((item) => item.key === key)[0].value;
    return result;
  };

  const BindingChangeInput = (key: string, value: string) => {
    const temp = operationRow;
    Object.entries(temp).map(([key1]) => {
      if (key1 === key) {
        temp[key] = value;
      }
    });
    setOperationRow(temp);
  };

  const BindingChangeSelect = async (key: string, type: any, param: any) => {
    const temp = operationRow;
    const selectValue = type.filter((item: any) => item.value === param)[0]
      .label;
    Object.entries(temp).map(([key1]) => {
      if (key1 === key) {
        temp[key] = selectValue;
      }
    });
    setOperationRow(temp);
  };

  const submit = () => {
    let flag = false;
    Object.entries(operationRow).map(([key, value]) => {
      if (value === "" && FormItemSet(key) !== "unused") {
        flag = true;
      }
    });
    if (flag) {
      message.error("請確保填寫完整數據");
      return false;
    }
    form.resetFields();
    props.Submit(operationRow, props.operation);
  };

  /**
   *
   * @returns 渲染表單。類型:input/textarea/select/input-disabled/human
   */
  //#region 表單
  const getForm = () => {
    const children: any = [];
    // eslint-disable-next-line @typescript-eslint/no-unused-vars
    Object.entries(props.singleRow).map(([key, _value]) => {
      const type = FormItemSet(key);
      const disabled =
        disabledSet.findIndex((item) => item === key) !== -1 &&
        props.operation === "modify" && props.check_flag
          ? true
          : false;
      switch (type) {
        case "input":
          children.push(
            <Col span={8} key={key}>
              <Form.Item
                name={key}
                label={
                  <label style={{ color: "black" }}>{FormItemLabel(key)}</label>
                }
                labelAlign="left"
                labelCol={{ span: 7 }}
              >
                <Input
                  onChange={(e) => {
                    BindingChangeInput(key, e.target.value);
                  }}
                  style={{
                    width: "250px",
                    color: disabled ? "#3b3131" : "black",
                  }}
                  maxLength={30}
                  disabled={disabled}
                ></Input>
              </Form.Item>
            </Col>
          );
          break;
        case "textarea":
          children.push(
            <Col span={24} key={key} style={{ margin: "10px 0" }}>
              <Form.Item
                name={key}
                label={
                  <label style={{ color: "black", width: "120px" }}>
                    {FormItemLabel(key)}
                  </label>
                }
                labelAlign="left"
                labelCol={{ span: 3 }}
              >
                <TextArea
                  onChange={(e) => {
                    BindingChangeInput(key, e.target.value);
                  }}
                  rows={3}
                  style={{
                    width: "780px",
                    right: "-1.5%",
                    color: disabled ? "#3b3131" : "black",
                  }}
                  disabled={disabled}
                  maxLength={3000}
                ></TextArea>
              </Form.Item>
            </Col>
          );
          break;
        case "input-disabled":
          children.push(
            <Col span={8} key={key}>
              <Form.Item
                name={key}
                label={
                  <label style={{ color: "black" }}>{FormItemLabel(key)}</label>
                }
                labelAlign="left"
                labelCol={{ span: 7 }}
              >
                <Input
                  style={{
                    width: "250px",
                    color: "black",
                  }}
                  maxLength={30}
                  disabled
                ></Input>
              </Form.Item>
            </Col>
          );
          break;
        case "input-disabled-double":
          children.push(
            <Col span={16} key={key}>
              <Form.Item
                name={key}
                label={
                  <label style={{ color: "black" }}>{FormItemLabel(key)}</label>
                }
                labelAlign="left"
                labelCol={{ span: 3 }}
              >
                <span
                  style={{
                    color: "skyblue",
                    width: "600px",
                    display: "block",
                    border: "1px solid #7cb305",
                    minHeight: "28px",
                    lineHeight: "28px",
                    paddingLeft: "10px",
                    borderRadius: "4px",
                  }}
                >
                  {props.singleRow[key]}
                </span>
              </Form.Item>
            </Col>
          );
          break;
        case "select":
          children.push(
            <Col span={24} key={key} style={{ margin: "10px 0" }}>
              <Form.Item
                name={key}
                label={
                  <label style={{ color: "black", width: "120px" }}>
                    {FormItemLabel(key)}
                  </label>
                }
                labelAlign="left"
                labelCol={{ span: 3 }}
              >
                <Select
                  style={{
                    width: "250px",
                    right: "-1.5%",
                    color: disabled ? "#3b3131" : "black",
                  }}
                  optionFilterProp="label"
                  options={FormItemSelectOps(key)}
                  onChange={(e) =>
                    BindingChangeSelect(key, FormItemSelectOps(key), e)
                  }
                ></Select>
              </Form.Item>
            </Col>
          );
          break;
        case "datepicker":
          children.push(
            <Col span={24} key={key} style={{ margin: "10px 0" }}>
              <Form.Item
                name={key}
                label={
                  <label style={{ color: "black", width: "120px" }}>
                    {FormItemLabel(key)}
                  </label>
                }
                labelAlign="left"
                labelCol={{ span: 3 }}
              >
                <DatePicker
                  onChange={(e) => {
                    BindingChangeInput(key, e.format("YYYY-MM-DD"));
                  }}
                  style={{
                    width: "250px",
                    right: "-1.5%",
                    color: disabled ? "#3b3131" : "black",
                  }}
                  maxLength={30}
                  disabled={disabled}
                ></DatePicker>
              </Form.Item>
            </Col>
          );
          break;
      }
    });
    return children;
  };
  //#endregion

  return (
    <Form form={form} style={{ marginTop: "30px", minWidth: "100%" }}>
      <Row>{getForm()}</Row>
      <Row gutter={24}>
        <Col span={24} style={{ textAlign: "center", marginTop: "20px" }}>
          <Form.Item>
            <Button
              type="primary"
              onClick={() => {
                submit();
              }}
              style={{ marginRight: "20px" }}
            >
              確定
            </Button>
            <Button
              color="danger"
              variant="solid"
              onClick={() => {
                form.resetFields();
                props.Cancle();
              }}
            >
              取消
            </Button>
          </Form.Item>
        </Col>
      </Row>
    </Form>
  );
}
